package top.huhuiyu.springboot.study.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot.study.config.MxnzpConfig;
import top.huhuiyu.springboot.study.entity.joke.NewsDetail;
import top.huhuiyu.springboot.study.entity.joke.NewsList;
import top.huhuiyu.springboot.study.entity.joke.NewsType;
import top.huhuiyu.springboot.study.entity.joke.TbNewsApiInfo;
import top.huhuiyu.springboot.study.mapper.joke.TbNewsApiInfoMapper;
import top.huhuiyu.springboot.study.service.NewsApiService;
import top.huhuiyu.springboot.study.util.JsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 胡辉煜
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class NewsApiServiceImpl implements NewsApiService {
  private final RestTemplate restTemplate;
  private final TbNewsApiInfoMapper tbNewsApiInfoMapper;

  @Override
  public int saveNews() {
    final int[] count = new int[]{0};
    // 基础配置的部分
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APPID);
    headers.add("app_secret", MxnzpConfig.APPSECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    // 第一步，获取新闻分类========================================
    String typeurl = MxnzpConfig.NEWS_TYPE_URL;
    String typeresult = restTemplate.exchange(typeurl, HttpMethod.GET, entity, String.class).getBody();
    log.debug("分类请求的url：{}", typeurl);
    log.debug("分类请求结果：{}", typeresult);
    NewsType newsType = JsonUtils.parse(typeresult, NewsType.class);
    // 第二步，获取新闻列表========================================
    newsType.getData().forEach(newsTypeData -> {
      sleepTwoSeconds();
      String listurl = String.format(MxnzpConfig.NEWS_LIST_URL, newsTypeData.getTypeId(), 1);
      String listresult = restTemplate.exchange(listurl, HttpMethod.GET, entity, String.class).getBody();
      log.debug("列表请求的url：{}", listurl);
      log.debug("列表请求结果：{}", listresult);
      NewsList newsList = JsonUtils.parse(listresult, NewsList.class);
      // 第三步，获取新闻详情========================================
      newsList.getData().forEach(newsListData -> {
        sleepTwoSeconds();
        String detailurl = String.format(MxnzpConfig.NEWS_DETAIL_URL, newsListData.getNewsId());
        String detailresult = restTemplate.exchange(detailurl, HttpMethod.GET, entity, String.class).getBody();
        log.debug("详情请求的url：{}", detailurl);
        log.debug("详情请求结果：{}", detailresult);
        NewsDetail newsDetail = JsonUtils.parse(detailresult, NewsDetail.class);
        // 第四步，组织新闻信息
        TbNewsApiInfo info = new TbNewsApiInfo();
        info.setTypeName(newsTypeData.getTypeName());
        info.setTitle(newsListData.getTitle());
        info.setSource(newsListData.getSource());
        info.setDigest(newsListData.getDigest());
        info.setPostTime(newsListData.getPostTime());
        info.setNewsId(newsListData.getNewsId());
        // 内容是数组，需要循环读取拼接
        StringBuilder sb = new StringBuilder();
        newsDetail.getData().getItems().forEach(newsDetailItem -> {
          // 文本内容，用段落标记包含
          if ("text".equalsIgnoreCase(newsDetailItem.getType())) {
            sb.append(String.format("<p>%s</p>", newsDetailItem.getContent()));
          } else if ("img".equalsIgnoreCase(newsDetailItem.getType())) {
            sb.append(String.format("<img src='%s'>", newsDetailItem.getImageUrl()));
          }
        });
        info.setContent(sb.toString());
        tbNewsApiInfoMapper.insert(info);
        count[0]++;
      });

    });

    return count[0];
  }


  private void sleep(int time) {
    try {
      Thread.sleep(time * 1000L);
    } catch (Exception ex) {
      log.debug("无需关注的休眠异常：{}", ex.getMessage());
    }
  }

  private void sleepTwoSeconds() {
    sleep(2);
  }

  @Override
  public NewsType getNewsType() {
    sleepTwoSeconds();
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APPID);
    headers.add("app_secret", MxnzpConfig.APPSECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String result = restTemplate.exchange(MxnzpConfig.NEWS_TYPE_URL, HttpMethod.GET, entity, String.class).getBody();
    log.debug("新闻分类查询：{}", result);
    return JsonUtils.parse(result, NewsType.class);
  }

  @Override
  public List<NewsList> getNewsList(NewsType newsType) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APPID);
    headers.add("app_secret", MxnzpConfig.APPSECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    List<NewsList> list = new ArrayList<>();

    newsType.getData().forEach(type -> {
      sleepTwoSeconds();
      String url = String.format(MxnzpConfig.NEWS_LIST_URL, type.getTypeId(), 1);
      String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
      log.debug("新闻列表查询：{}", result);
      list.add(JsonUtils.parse(result, NewsList.class));
    });
    return list;
  }


}
